<?php
/**
*    Images Saler - Component
*    Author : hm_advert@ymail.com
*    
**/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.client.helper');
jimport('joomla.application.component.model');
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . "libs" . DS . "functions.php");

class EcommerceModelRegister extends JModel
{
	
	var $_id = null;
	var $_table = '#__pr_product';
	var $_lists = '';
	var $_data = null;
		
	function __construct()
	{
		parent::__construct();

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
		
	}

	function setId($id)
	{
		$this->_id		= $id;
	}
	
	function getUser($user_id){
		$query = ' SELECT * FROM #__users '.
				'  WHERE id = '.$user_id;
				
		$this->_db->setQuery( $query );
		return $this->_db->loadObject();
	}
	
	function &getData()
	{
		if (empty( $this->_data )) 
		{
			$query = ' SELECT * FROM #__pr_product '.
					'  WHERE id = '.$this->_id;
					
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();	
			
		}

		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->type = null;
			$this->_data->model = null;
			$this->_data->register_day = null;
			$this->_data->short_description= null;
			$this->_data->view_day = null;
			$this->_data->registry = null;
			$this->_data->stand = null;
			$this->_data->km = null;
			$this->_data->description = null;
			$this->_data->information1 = null;
			$this->_data->information2 = null;
			$this->_data->image = null;
			$this->_data->image1 = null;
			$this->_data->image2 = null;
			$this->_data->image3 = null;
			$this->_data->image4 = null;
			$this->_data->ordering = null;
			$this->_data->published = null;
			
		}
		return $this->_data;
	}
	
	function getImages(){
		$query = "SELECT id,name FROM #__pr_image WHERE product_id = ".$this->_id." ORDER BY id";
		$this->_db->setQuery($query);
		$images = $this->_db->loadObjectList();
		
		return $images;
	}

	function store()	{
		global $mainframe;
		$row =& $this->getTable();
		if(!$row->bind(JRequest::get('post'))){
			echo '<script>alert("'.$row->getError().'");window.history.go(-1);</script>\n';
			exit();
		}
		
		//all these lines are used to avoid lost data form post
		$row->model = JRequest::getVar('model');
		$row->desired_price = JRequest::getVar('desired_price');
		$row->placering = JRequest::getVar('placering');
		$row->car_type = JRequest::getVar('car_type');
		$row->fuel = JRequest::getVar('fuel');
		$row->type = intval(JRequest::getVar('type'));//print_r($row->type);exit();
		$row->register_day = JRequest::getVar('register_day');
		$row->view_day = JRequest::getVar('view_day');
		$row->registry = JRequest::getVar('registry');
		$row->stand = JRequest::getVar('stand');
		$row->km = JRequest::getVar('km');
		$row->carid = JRequest::getVar('carid');
		$row->katno = JRequest::getVar('katno');
		
		$row->comment  = JRequest::getVar('comment','','post','string',JREQUEST_ALLOWRAW);
		
		$row->color = JRequest::getVar('color');
		$row->color_type = JRequest::getVar('color_type');
		$row->cabin_color = JRequest::getVar('cabin_color');
		$row->chassis = JRequest::getVar('chassis');
		
		$row->abs = JRequest::getVar('abs',' ');
		$row->alarm = JRequest::getVar('alarm',' ');
		$row->antispin = JRequest::getVar('antispin',' ');
		$row->start = JRequest::getVar('start',' ');
		$row->esp = JRequest::getVar('esp',' ');
		$row->airbag = JRequest::getVar('airbag');
		$row->armrest = JRequest::getVar('armrest',' ');
		$row->split_seat = JRequest::getVar('split_seat',' ');
		$row->wood = JRequest::getVar('wood',' ');
		$row->leather_steering = JRequest::getVar('leather_steering',' ');
		$row->seat_cover = JRequest::getVar('seat_cover');
		$row->flexible = JRequest::getVar('flexible');
		if(JRequest::getVar('stand_tire')){
			$row->stand_tire = JRequest::getVar('stand_tire');
			$row->alu_tire = '';
		}
		if(JRequest::getVar('alu_tire')){
			$row->alu_tire = JRequest::getVar('alu_tire');
			$row->stand_tire = '';
		}
		$row->tread = JRequest::getVar('tread');
		
		$row->air_con = JRequest::getVar('air_con',' ');
		$row->elc_heat_mirror = JRequest::getVar('elc_heat_mirror',' ');
		$row->sensor = JRequest::getVar('sensor',' ');
		$row->automatic = JRequest::getVar('automatic',' ');
		$row->elec_seat = JRequest::getVar('elec_seat',' ');
		$row->radio = JRequest::getVar('radio',' ');
		$row->central = JRequest::getVar('central',' ');
		$row->cruise = JRequest::getVar('cruise',' ');
		$row->servo = JRequest::getVar('servo',' ');
		$row->remote = JRequest::getVar('remote',' ');
		$row->gps = JRequest::getVar('gps',' ');
		$row->sunroof = JRequest::getVar('sunroof',' ');
		$row->power_window = JRequest::getVar('power_window',' ');
		$row->air_con1 = JRequest::getVar('air_con1',' ');
		$row->elec_sunroof = JRequest::getVar('elec_sunroof',' ');
		$row->elec_mirror = JRequest::getVar('elec_mirror',' ');
		$row->computer = JRequest::getVar('computer',' ');
		$row->heated_seat = JRequest::getVar('heated_seat',' ');
		$row->power_steering = JRequest::getVar('power_steering',' ');
		$row->bak_sensor = JRequest::getVar('bak_sensor',' ');
		$row->elec_adj_seat = JRequest::getVar('elec_adj_seat',' ');
		$row->heated_mirror = JRequest::getVar('heated_mirror',' ');
		
		$row->towbar = JRequest::getVar('towbar',' ');
		$row->lower = JRequest::getVar('lower',' ');
		$row->fog_light = JRequest::getVar('fog_light',' ');
		$row->removable_towbar = JRequest::getVar('removable_towbar',' ');
		$row->xenon = JRequest::getVar('xenon',' ');
		$row->roof_rail = JRequest::getVar('roof_rail',' ');
		$row->lamp_washer = JRequest::getVar('lamp_washer',' ');
		$row->spoiler = JRequest::getVar('spoiler',' ');
		
		$row->clean = JRequest::getVar('clean');
		$row->clean_content = JRequest::getVar('clean_content');
		$row->interior_defect = JRequest::getVar('interior_defect');
		$row->external = JRequest::getVar('external');
		$row->front = JRequest::getVar('front');
		$row->rear = JRequest::getVar('rear');
		$row->left_err = JRequest::getVar('left');
		$row->right_err = JRequest::getVar('right');
		
		$row->machinal_defect = JRequest::getVar('machinal_defect');
		$row->electrical_defect = JRequest::getVar('electrical_defect');
		$row->service_book = JRequest::getVar('service_book');
		$row->belt = JRequest::getVar('belt');
		$row->front_brake = JRequest::getVar('front_brake');
		$row->rear_brake = JRequest::getVar('rear_brake');
		$row->exhaust = JRequest::getVar('exhaust');
		
		$row->repainted = JRequest::getVar('repainted');
		$row->parking_damage = JRequest::getVar('parking_damage');
		$row->accident = JRequest::getVar('accident');
		
		$row->ordering = intval(JRequest::getVar('ordering'));
		$row->published = intval(JRequest::getVar('published'));
		if(JRequest::getVar('user_id')){
			$row->user_id = JRequest::getVar('user_id');
		} else {
			$name = JRequest::getVar('name');
			$email = JRequest::getVar('email');
			$company = JRequest::getVar('company');
			$cvr = JRequest::getVar('cvr');
			$address = JRequest::getVar('address');
			$code = JRequest::getVar('code');
			$city = JRequest::getVar('city');
			$phone = JRequest::getVar('phone');
			$query = "INSERT INTO #__users(name, email, company, cvr, address, code, city, phone, post) VALUES ('".$name."', '".$email."', '".$company."', '".$cvr."', '".$address."', '".$code."', '".$city."', '".$phone."', 1)";
			$this->_db->setQuery($query);
			$this->_db->query();
			$row->user_id = $this->_db->insertid(); 
		}
		$row->approve = JRequest::getVar('approve');
		$row->bought = JRequest::getVar('bought');
		if($_FILES['txtimage']['name']){
			$rand_image = mt_rand();
			$row->image = $rand_image.$_FILES['txtimage']['name'];
		}
		if($_FILES['txtimage1']['name']){
			$rand_image1 = mt_rand();
			$row->image1 = $rand_image1.$_FILES['txtimage1']['name'];
		}
		if($_FILES['txtimage2']['name'])
		{
			$rand_image2 = mt_rand();
			$row->image2 = $rand_image2.$_FILES['txtimage2']['name'];
		}
		if($_FILES['txtimage3']['name'])
		{
			$rand_image3 = mt_rand();
			$row->image3 = $rand_image3.$_FILES['txtimage3']['name'];
		}
		if($_FILES['txtimage4']['name'])
		{
			$rand_image4 = mt_rand();
			$row->image4 = $rand_image4.$_FILES['txtimage4']['name'];
		}	
		
		$row->alias = JFilterOutput::stringURLSafe($row->model);
		//print_r($row);exit();	
		if(!$row->store()){
			echo '<script>alert("'.$row->getError().'");window.history.go(-1);</script>';
			exit();
		}
		else
		{
			$row->checkin();
			$row->reorder();
			$prodir = "../components/com_ecommerce/imgupload/";
			$upload = new se_upload();
				
			$pro_image = JRequest::getVar('image','','post','string');
			$upload->new_upload('txtimage', 1000000000);
			if(($upload->is_error == 0))
			{	
				if($pro_image!="")
				{
					unlink($prodir.$pro_image);
				} 
				$desphoto = $prodir.$rand_image.$upload->file_name;
				move_uploaded_file($upload->file_tempname, $desphoto);
			}
			
			$pro_image1 = JRequest::getVar('image1','','post','string');
			$upload->new_upload('txtimage1', 1000000000);
			if(($upload->is_error == 0))
			{	
				if($pro_image1!="")
				{
					unlink($prodir.$pro_image1);
				} 
				$desphoto = $prodir.$rand_image1.$upload->file_name;
				move_uploaded_file($upload->file_tempname, $desphoto);
			}
			
			$pro_image2 = JRequest::getVar('image2','','post','string');
			$upload->new_upload('txtimage2', 1000000000);
			if(($upload->is_error == 0))
			{	
				if($pro_image2!="")
				{
					unlink($prodir.$pro_image2);
				} 
				$desphoto = $prodir.$rand_image2.$upload->file_name;
				move_uploaded_file($upload->file_tempname, $desphoto);
			}
			
			$pro_image3 = JRequest::getVar('image3','','post','string');
			$upload->new_upload('txtimage3', 1000000000);
			if(($upload->is_error == 0))
			{	
				if($pro_image3!="")
				{
					unlink($prodir.$pro_image3);
				} 
				$desphoto = $prodir.$rand_image3.$upload->file_name;
				move_uploaded_file($upload->file_tempname, $desphoto);
			}
			
			$pro_image4 = JRequest::getVar('image4','','post','string');
			$upload->new_upload('txtimage4', 1000000000);
			if(($upload->is_error == 0))
			{	
				if($pro_image4!="")
				{
					unlink($prodir.$pro_image4);
				} 
				$desphoto = $prodir.$rand_image4.$upload->file_name;
				move_uploaded_file($upload->file_tempname, $desphoto);
			}
			
			$num = JRequest::getVar('imageNum');
			if($num){
				for($i = 0; $i<$num; $i++){
					if($_FILES['imageadd'.$i]['name']){
						if(JRequest::getVar('imageold'.$i)){
							$query = "DELETE FROM #__pr_image WHERE name = '".JRequest::getVar('imageold'.$i)."'";
							$this->_db->setQuery($query);
							$this->_db->query();
							unlink($prodir.JRequest::getVar('imageold'.$i));
						}
						$rand = mt_rand();
						$nameArr[$i] = $rand.$_FILES['imageadd'.$i]['name'];
						$desphoto = $prodir.$rand.$_FILES['imageadd'.$i]['name'];
						move_uploaded_file($_FILES['imageadd'.$i]['tmp_name'], $desphoto);
					}
				}
			}
			$proid = $row->id;
			foreach($nameArr as $imgName){
				$query = "INSERT INTO #__pr_image (name, product_id) VALUES ('".$imgName."', ".$proid.")";
				$this->_db->setQuery($query);
				$this->_db->query();
			}
			return true;
		}
	}

	function delete()
	{
		global $mainframe;
		$cid = JRequest::getVar('cid',array(),'','array');
		$db = JFactory::getDBO();
		if(count($cid)> 0 )
		{
			$cids = implode(',',$cid);

			$query = "select * from #__pr_product where id in ($cids)";
			$db->setQuery($query);
			$row = $db->loadObjectList();
						
			foreach ($row as $_file)
			{
				$prodir = "../components/com_ecommerce/imgupload/";
				
				$query = "SELECT name FROM #__pr_image WHERE product_id = ".$_file->id;
				$db->setQuery($query);
				$images = $db->loadResultArray();
				foreach($images as $image){
					unlink($prodir . $image);
				}
				$query = "DELETE FROM #__pr_image WHERE product_id = ".$_file->id;
				$db->setQuery($query);
				$db->query();
				
				if(file_exists($prodir . $_file->image))
				{
					unlink($prodir . $_file->image);
				}
				if(file_exists($prodir . $_file->image1))
				{
					unlink($prodir . $_file->image1);
				}
				if(file_exists($prodir . $_file->image2))
				{
					unlink($prodir . $_file->image2);
				}
				if(file_exists($prodir . $_file->image3))
				{
					unlink($prodir . $_file->image3);
				}
				if(file_exists($prodir . $_file->image4))
				{
					unlink($prodir . $_file->image4);
				}
			}
			$query = "DELETE FROM #__pr_product WHERE id in ($cids)";
			$db->setQuery($query);
			if(!$db->query())
			{
				echo "<script> alert('".$db->getErrorMsg()."');window.history.go(-1); </script>\n";
			}
			$row =& $this->getTable();
			$row->checkin();
			$row->reorder();
		}

		return true;
	}

	function publish($publish) {
		$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		JArrayHelper::toInteger($cid);
	
		if ( count( $cid ) < 1 ) {
			$action = $publish ? 'Publish' : 'Unpublish';
			JError::raiseError(500, JText::_( 'Select Item to '.$action, true ) );
		}
		
		$cids = implode( ',', $cid );
		$count = count( $cid );
		$query = 'UPDATE #__pr_product'
		. ' SET published = '.(int) $publish
		. ' WHERE id IN ( '.$cids.' )'
		;

		$db =& JFactory::getDBO();
		$db->setQuery( $query );
		if (!$db->query()) {
			JError::raiseError(500, $db->getErrorMsg() );
		}
	
	}
	
	function approve($publish) {
		$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		JArrayHelper::toInteger($cid);
	
		if ( count( $cid ) < 1 ) {
			$action = $publish ? 'Approve' : 'Unapprove';
			JError::raiseError(500, JText::_( 'Select Item to '.$action, true ) );
		}
		
		$cids = implode( ',', $cid );
		$count = count( $cid );
		$query = 'UPDATE #__pr_product'
		. ' SET approve = '.(int) $publish
		. ' WHERE id IN ( '.$cids.' )'
		;

		$db =& JFactory::getDBO();
		$db->setQuery( $query );
		if (!$db->query()) {
			JError::raiseError(500, $db->getErrorMsg() );
		}
	
	}
	
	function bought($publish) {
		$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		JArrayHelper::toInteger($cid);
	
		if ( count( $cid ) < 1 ) {
			$action = $publish ? 'Bought' : 'Unbought';
			JError::raiseError(500, JText::_( 'Select Item to '.$action, true ) );
		}
		
		$cids = implode( ',', $cid );
		$count = count( $cid );
		$query = 'UPDATE #__pr_product'
		. ' SET bought = '.(int) $publish
		. ' WHERE id IN ( '.$cids.' )'
		;

		$db =& JFactory::getDBO();
		$db->setQuery( $query );
		if (!$db->query()) {
			JError::raiseError(500, $db->getErrorMsg() );
		}
	
	}
	
	function orderSection( $uid, $inc)
	{
		$row =& $this->getTable();
		$row->load( $uid );
		$row->move( $inc);
	}

	function saveOrder( &$cid )
	{
		$row =& $this->getTable();
	
		$total		= count( $cid );
		$order		= JRequest::getVar( 'order', array(0), 'post', 'array' );
		JArrayHelper::toInteger($order, array(0));
	
		// update ordering values
		for( $i=0; $i < $total; $i++ )
		{
			$row->load( (int) $cid[$i] );
			if ($row->ordering != $order[$i]) {
				$row->ordering = $order[$i];
				if (!$row->store()) {
					JError::raiseError(500, $db->getErrorMsg() );
				}
			}
		}
	
		$row->reorder();
	}
}

?>